package cn.yitun.chat.yitunserverimcore.general.aspect;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yituncommonweb.util.YitunHttpUtil;
import cn.yitun.chat.yitunservercommonlib.annotation.Log;
import cn.yitun.chat.yitunservercommonlib.basebean.web.JwtUserDto;
import cn.yitun.chat.yitunservercommonlib.constant.Constants;
import cn.yitun.chat.yitunservercommonlib.context.FilterContextHandler;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.common.SyslogDto;
import cn.yitun.chat.yitunservercommonlib.util.HttpContextUtils;
import cn.yitun.chat.yitunservercommonlib.util.JwtUtil;
import cn.yitun.chat.yitunserverimcore.general.common.service.common.LogService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 操作日志功面
 * 只在httpweb请求时适用
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogService logService;

    private static final Gson gson = new GsonBuilder().create();

    @Pointcut("@annotation(cn.yitun.chat.yitunservercommonlib.annotation.Log)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        saveLog(point, time);
        return result;
    }

    void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SyslogDto operateLog = new SyslogDto();
        Log syslog = method.getAnnotation(Log.class);
        if (syslog != null) {
            // 注解上的描述
            operateLog.setOperation(syslog.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        operateLog.setMethod(className + "." + methodName + "()");
        if (syslog.storeParams()) {
            // 请求的参数
            Object[] args = joinPoint.getArgs();
            try {
                if (args != null && args.length > 0) {
                    if (args[0] != null) {
                        String params = gson.toJson(args[0]);
                        operateLog.setParams(params);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String accessToken = request.getHeader(Constants.TOKEN);
        if (YitunStringUtil.isEmpty(accessToken) )
            return ;
        FilterContextHandler.setToken(accessToken);
        // 设置IP地址
        operateLog.setIp(YitunHttpUtil.getIpAddr(request));
        // 用户名
        JwtUserDto attribute;
        try {
//            String decrypt = JwtUtil.decrypt(jwtToken);
            Claims claims = JwtUtil.parseJWT(accessToken);
            String decrypt = claims.getSubject();
            attribute = new Gson().fromJson(decrypt, JwtUserDto.class);
        } catch (Exception e) {
            throw new YitunException(ExceptionEnum.DECRYPT_USER_INFO_ERROR);
        }
        if (null == attribute) {
            operateLog.setUserId(-1l);
            if (null != operateLog.getParams()) {
                operateLog.setUsername(operateLog.getParams().substring(0,50));
            } else {
                operateLog.setUsername("获取用户信息为空");
            }
        } else {
            operateLog.setUserId(attribute.getUserId());
            operateLog.setUsername(attribute.getUsername());
        }
        operateLog.setTime((int) time);
        // 保存系统日志
        logService.save(operateLog);
    }
}
